package 数据结构.章节10._170_实现HashSet;

import 数据结构.章节10._168_实现HashMap.MyHashMap;
import 数据结构.章节10._168_实现HashMap.Node;

import java.util.Iterator;

/**
 * @author 挚爱之夕
 * @date 2021/10/16 - 10 - 16 - 16:53
 * @Description: 数据结构.章节10._170_实现HashSet
 * @Version: 1.0
 */
public class MyHashSet<E> implements IHashSet<E>{
    private MyHashMap<E,E> map = new MyHashMap<>();
    @Override
    public void add(E key) {
        map.put(key, null);
    }

    @Override
    public void remove(E key) {
        map.remove(key);
    }

    @Override
    public void clear() {
        map.clear();
    }

    @Override
    public boolean contains(E key) {
        return map.containsKey(key);
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public String toString() {
//        StringBuilder sb = new StringBuilder("[");
//        E[] es = map.keySet();
//        if(es == null)
//            return "[]";
//        for (E e : es) {
//            sb.append(e).append(",");
//        }
//        sb = new StringBuilder(sb.substring(0,sb.length()-1));
//        sb.append("]");
//        return sb.toString();
        StringBuilder sb = new StringBuilder("[");
        Iterator<Node> iterator = map.iterator() ;
        while(iterator.hasNext()){
            sb.append(iterator.next().key).append(",");
        }
        if(sb.charAt(sb.length()-1)==','){
            sb = new StringBuilder(sb.substring(0,sb.length()-1));
        }
        sb.append("]");
        return sb.toString();
    }
}
